/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.net;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;

/**
 * HttpUtils
 */
public class HttpUtils {
    public static void httpGet(String urlStr, HttpCallBackListener listener) {
        StringBuilder sb = new StringBuilder();
        try {
            // 添加https信任
            // 第一个参数为协议,第二个参数为提供者(可以缺省)
            SSLContext sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(null, null, new SecureRandom());
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);
            // 此两条少了就会 "Forbid spider access"
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0");

            connection.connect();
            int code = connection.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String temp;
                while ((temp = reader.readLine()) != null) {
                    sb.append(temp);
                }
                reader.close();
            }
            connection.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
            listener.onFailure(ex);
            return;
            // return e.getMessage();
        }
        listener.onResponse(sb.toString());
        return;
        // return sb.toString();
    }
}
